package.path = package.path .. ";/usr/local/share/lua/5.3/?.lua"
package.cpath = package.cpath .. ";/usr/local/lib/lua/5.3/?.so"
require('init')
local luasql = require('luasql.mysql')
local cjson = require("cjson")

--加载配置文件
local function load_config_file(filename)
    file = io.open(filename)
    if not file then
        error("open " .. filename .. " failed: " .. (err or "unknown error"))
        return
    end
    local content = file:read('*a')
    file:close()
    return cjson.decode(content)
end

local config = load_config_file("../config/config.json")

-- MySQL配置
local mysql_db = config.mysql_db
local mysql_username = config.mysql_username
local mysql_password = config.mysql_password
local mysql_host = config.mysql_host
local mysql_port = config.mysql_port

--创建环境对象
local env = luasql.mysql()

--连接数据库
local conn,err = env:connect(mysql_db,mysql_username,mysql_password,mysql_host,mysql_port)
if not conn then
    error("connect to database failed: " .. err)
    return
else
    print("connect mysql server success")
end

--设置数据库的编码格式
conn:execute("set names utf-8")


function login(username,password)
    local sql = string.format("SELECT * FROM user_accounts WHERE username = '%s' AND password = '%s'", username, password)

    local cur, error_msg = conn:execute(sql)

    if not cur then
        error("Failed to execute query: " .. error_msg)
    end

    local row = cur:fetch({}, "a")

    if not row then
        return false,"用户名/密码错误"
    else
        return true,"登录成功"
    end
end